#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import time
import json
import logging
from datetime import datetime

# 添加项目根目录到sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from services.exchange.adapters.gate_adapter import GateAdapter

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def handle_ticker_update(data):
    """
    处理ticker数据更新
    
    参数:
        data: ticker数据列表
    """
    for ticker in data:
        contract = ticker.get('contract', '')
        last = ticker.get('last', '')
        mark_price = ticker.get('mark_price', '')
        index_price = ticker.get('index_price', '')
        
        logger.info(f"收到Ticker更新 - 合约: {contract}, 最新价: {last}, 标记价: {mark_price}, 指数价: {index_price}")

def handle_kline_update(data):
    """
    处理K线数据更新
    
    参数:
        data: K线数据列表
    """
    for kline in data:
        contract = kline.get('n', '')  # n代表合约名称
        timestamp = kline.get('t', 0)  # t代表时间戳
        close = kline.get('c', '')  # c代表收盘价
        
        time_str = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
        logger.info(f"收到K线更新 - 合约: {contract}, 时间: {time_str}, 收盘价: {close}")

def main():
    """主函数"""
    # 初始化Gate适配器，使用测试网
    gate = GateAdapter(use_testnet=True)
    
    try:
        # 订阅BTC_USDT的ticker数据
        logger.info("订阅BTC_USDT的ticker数据...")
        if gate.subscribe_ticker("BTC-USDT", handle_ticker_update):
            logger.info("订阅ticker成功")
        else:
            logger.error("订阅ticker失败")
        
        # 订阅BTC_USDT的5分钟K线数据
        logger.info("订阅BTC_USDT的5分钟K线数据...")
        if gate.subscribe_kline("BTC-USDT", "5m", handle_kline_update):
            logger.info("订阅K线成功")
        else:
            logger.error("订阅K线失败")
        
        # 保持程序运行
        logger.info("开始接收数据，按Ctrl+C退出...")
        while True:
            time.sleep(1)
            
    except KeyboardInterrupt:
        logger.info("程序被用户中断")
    finally:
        # 关闭所有连接
        logger.info("关闭WebSocket连接...")
        gate.close_all_ws_connections()
        logger.info("程序退出")

if __name__ == "__main__":
    main() 